package it.lupo.model.service;

import it.lupo.model.BarCode;
import it.lupo.repository.HibernateSessionFactory;
import it.lupo.repository.dao.BarCodeDAO;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class BarCodeService {

private static BarCodeService instance;
	
	private BarCodeService(){}
	
	public static BarCodeService getInstance()
	{
		if(instance==null)
			instance=new BarCodeService();
		return instance;
	}
	
	public BarCode check(String code)
	{
		Session session = HibernateSessionFactory.getSession();
		Transaction trx = session.beginTransaction();
		try{		
			BarCodeDAO udao = new BarCodeDAO();
			BarCode barcode = udao.findByBarCode(code);
			
			trx.commit();
			session.close();
			return barcode!=null?barcode:null;
		}catch(Exception e)
		{
			e.printStackTrace();
			trx.rollback();
			session.close();
			return null;
		}
	}
	
	
	public List<BarCode> getLasts(int maxResults)
	{
		Session session = HibernateSessionFactory.getSession();
		Transaction trx = session.beginTransaction();
		try{
			
			BarCodeDAO udao = new BarCodeDAO();
			List<BarCode> lists = udao.findLasts(maxResults);
			
			trx.commit();
			session.close();
			return lists;
			
		}catch(Exception e)
		{
			e.printStackTrace();
			trx.rollback();
			session.close();
			return null;
		}
	}
	
//	public static void main(String []args)
//	{
//		BarCode bc = new BarCode("123456", "GRCDNC86M21G786X", "Domenico","Grieco","Via Bottalico","",true);
//		BarCodeService.getInstance().create(bc);
//	}

	public BarCode create(BarCode code) {
		Session session = HibernateSessionFactory.getSession();
		Transaction trx = session.beginTransaction();
		try{
			
			BarCodeDAO udao = new BarCodeDAO();
			udao.create(code);
			
			trx.commit();
			session.close();
			return code;
			
		}catch(Exception e)
		{
			e.printStackTrace();
			trx.rollback();
			session.close();
			return null;
		}
		
	}
	
	public BarCode update(BarCode code) {
		
		Session session = HibernateSessionFactory.getSession();
		Transaction trx = session.beginTransaction();
		try{
			BarCodeDAO udao = new BarCodeDAO();
			udao.update(code);
			
			trx.commit();
			session.close();
			return code;
		}catch(Exception e)
		{
			e.printStackTrace();
			trx.rollback();
			session.close();
			return null;
		}
		
		
	}

	public void delete(BarCode code) {
		Session session = HibernateSessionFactory.getSession();
		Transaction trx = session.beginTransaction();
		try{
			BarCodeDAO udao = new BarCodeDAO();
			udao.delete(code);
			
			trx.commit();
			session.close(); 
		}catch(Exception e)
		{
			e.printStackTrace();
			trx.rollback();
			session.close(); 
		}
		
		
	}
}
